package com.hzdesk.media.koreabatchmatvector.request;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;


import com.hzdesk.media.koreabatchmatvector.inter.BitmapCallBack;
import com.hzdesk.media.koreabatchmatvector.inter.ICallBack;
import com.hzdesk.media.koreabatchmatvector.utils.HttpUtil;
import com.hzdesk.media.koreabatchmatvector.utils.MacUtil;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static java.lang.String.valueOf;

/**
 * Created by Administrator on 2018/5/24.
 */

public class Model {
    private static Model instance = new Model();//单例

    public static Model getInstance() {
        return instance;
    }

    private ProgressDialog dialog;//显示下载的进度条

    public OkHttpClient client = HttpUtil.getClient();

    private String sessionId = "sessionId";
    private String sourceType = "sourceType";

    public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");

    /**
     * 异步get请求
     * 使用ICallBack接口传递返回数据
     *
     * @param context
     * @param url
     * @return
     * @throws Exception
     */
    public void getSynchronized(final Context context, final String url, final ICallBack callback) {
        Request request = new Request.Builder()
                .url(url)
                .addHeader(sessionId, MacUtil.getMacAddress(context))
                /*.addHeader(sessionId, "ac:35:ee:22:88:12")*/
                .addHeader(sourceType, "1")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.result(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callback.result(response.body().string());
                } else {
                    callback.result("请求失败！");
                }
            }
        });

    }

    /**
     * post方式提交Map
     * 使用ICallBack接口传递返回数据
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public void postMap(Context context, String url, Map<String, String> map, final ICallBack callback) {
        FormBody.Builder builder = new FormBody.Builder();
        if (map != null) {
            //增强for循环遍历
            for (Map.Entry<String, String> entry : map.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        FormBody formBody = builder.build();
        Request request = new Request.Builder()
                .addHeader(sessionId, MacUtil.getMacAddress(context))
                .addHeader(sourceType, "1")
                .post(formBody)
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.result(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callback.result(response.body().string());
                } else {
                    callback.result("请求失败！");
                }
            }
        });
    }

    /**
     * 异步post请求
     *
     * @param context
     * @param url
     * @param jsonString
     * @param callback
     */
    public void postSynchronized(final Context context, final String url, String jsonString, final ICallBack callback) {
        RequestBody requestBody = RequestBody.create(JSON, jsonString);
        Request request = new Request.Builder()
                .post(requestBody)
                .addHeader(sessionId, MacUtil.getMacAddress(context))
                .addHeader(sourceType, "1")
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.result(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callback.result(response.body().string());
                } else {
                    callback.result("请求失败！");
                }
            }
        });
    }


    public void post(Context context, String url, String jsonString, final ICallBack callback) {
        Log.d("Model",jsonString);
        RequestBody requestBody = RequestBody.create(JSON, jsonString);
        Request request = new Request.Builder()
                .addHeader(sessionId, MacUtil.getMacAddress(context))
                .addHeader(sourceType, "1")
                .url(url)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.result(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callback.result(response.body().string());
                } else {
                    callback.result("请求失败！");
                }
            }

        });

    }

    /**
     * 异步下载文件
     * BitmapCallBack接口进行数据传递
     *
     * @param context
     * @param url
     * @param name
     */
    public void downAsynFile(final Context context, String url, final String name, final BitmapCallBack callback) {
        //dialog = DialogUtil.getProgressDialog(context);
        //dialog.show();
        final Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e);
            }

            @Override
            public void onResponse(Call call, Response response) {
                /*if (response.isSuccessful()) {
                    InputStream inputStream = response.body().byteStream();//获取文件输入流
                    Bitmap bitmap = FileUtil.saveFile(name, inputStream);//获取的流进行文件操作
                    callback.imgBitmap(bitmap);
                    System.out.println("下载成功！");

                } else {
                    System.out.println("下载失败！");
                }
                response.close();//下载文件耗时较久，完成后需要手动关闭请求
               // dialog.dismiss();*/
            }
        });

    }

    /**
     * 上传图片
     *
     * @param context
     * @param url
     * @param requestBody
     * @param callback
     */
    public void uploadImage(Context context, String url, RequestBody requestBody, final ICallBack callback) {
        Request request = new Request.Builder()
                .addHeader(sessionId, MacUtil.getMacAddress(context))
                .addHeader(sourceType, "1")
                .url(url)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.result(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callback.result(response.body().string());
                } else {
                    callback.result("请求失败！");
                }
            }
        });
    }

    /**
     * 表单上传图片
     *
     * @param context
     * @param url
     * @param callback
     */
    public void UploadImageByMap(final Context context, final String url, File file, final ICallBack callback) {
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        requestBody.addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
        Request request = new Request.Builder()
                .addHeader(sessionId, MacUtil.getMacAddress(context))
                .addHeader(sourceType, "1")
                .post(requestBody.build())
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callback.result(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    callback.result(response.body().string());
                } else {
                    callback.result("请求失败！");
                }
            }
        });
    }
}
